package 华为OD机试真题2023.进阶题;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import utils.MyUtil;

public class HJ05_寻找符合要求的最长字串 {
  public static void main(String[] args) throws FileNotFoundException {
    MyUtil.START();
    Solution();
    //    Solution2();
    MyUtil.END();
  }

  static void Solution() throws FileNotFoundException {
    Scanner in = new Scanner(new File("src/main/java/华为OD机试真题2023/进阶题/input/05.txt"));
    char notInclude = in.nextLine().charAt(0);
    String s = in.nextLine();
    Map<Character, Integer> count = new HashMap<>();
    int tmp = 0, maxRes = 0;
    int l = 0;
    for (int i = 0; i < s.length(); i++) {
      char a = s.charAt(i);
      if (a == notInclude) {
        count.clear();
        maxRes = Math.max(maxRes, i - l);
        l = i + 1;
      } else {
        int times = count.getOrDefault(a, 0) + 1;
        while (times == 3) {
          char b = s.charAt(l);
          if (a == b) {
            l++;
            times--;
            break;
          }
          count.put(b, count.get(b) - 1);
          l++;
        }
        count.put(a, times);
        maxRes = Math.max(maxRes, i - l + 1);
      }
    }
    System.out.println(maxRes);
  }

  static void Solution2() throws FileNotFoundException {
    Scanner scanner = new Scanner(new File("src/main/java/华为OD机试真题2023/进阶题/input/05.txt"));
    char c = scanner.next().charAt(0);
    String s = scanner.next();
    test(c, s);
  }

  static void test(char c, String s) {
    int l = 0;
    int result = 0;
    Map<Character, Integer> map = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
      char temp = s.charAt(i);
      if (temp == c) {
        map.clear();
        l = i + 1;
        continue;
      }
      map.put(temp, map.getOrDefault(temp, 0) + 1);
      while (map.get(temp) == 3) {
        char rmStr = s.charAt(l);
        l++;
        map.put(rmStr, map.get(rmStr) - 1);
      }
      result = Math.max(result, i - l + 1);
    }
    System.out.println(result);
  }
}
